package com.deer.wms.base.system.model.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpClientss {
    private static Logger logger = LoggerFactory.getLogger(HttpClientss.class);

    public static String client(String url, HttpMethod method, MultiValueMap<String, String> params){
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        //  请勿轻易改变此提交方式，大部分的情况下，提交方式都是表单提交
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
        //  执行HTTP请求
        ResponseEntity<String> response = client.exchange(url, method, requestEntity, String.class);
        return response.getBody();
    }

    public static List clientList(String url, HttpMethod method, JSONObject params){
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        //  请勿轻易改变此提交方式，大部分的情况下，提交方式都是表单提交
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<JSONObject> requestEntity = new HttpEntity<>(params, headers);
        //  执行HTTP请求
        ResponseEntity<List> response = client.exchange(url, method, requestEntity, List.class);

        return response.getBody();
    }

    public static Map clientMap(String url, HttpMethod method, MultiValueMap<String, String> params){
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        //  请勿轻易改变此提交方式，大部分的情况下，提交方式都是表单提交
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
        //  执行HTTP请求
        ResponseEntity<Map> response = client.exchange(url, method, requestEntity, Map.class);
        return response.getBody();
    }

    /*public static void main(String[] args) {
        MultiValueMap<String, String> stringMultiValueMap = new LinkedMultiValueMap<>();
        stringMultiValueMap.add("taskNo", "123");

       String aaa=  HttpClient.client("https://www.zhihu.com/question/27400704",HttpMethod.GET,stringMultiValueMap);
       System.out.println(aaa);
    }*/


    public static Map<String, String> requestERP( String body, String url, HttpMethod method) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.add("access-token", "123456");
        HttpEntity<String> requestEntity = new HttpEntity<>(body, headers);
        RestTemplate client = new RestTemplate();
        ResponseEntity<String> response = client.exchange(url, method, requestEntity, String.class);
        String res = response.getBody();
        JSONObject object = JSON.parseObject(res);
        Boolean success = object.getBoolean("success");
        String code = object.getString("code");
        String msg = object.getString("message");
        Map<String, String> map = new HashMap<>();
        map.put("success", success != null ? success.toString() : "false");
        map.put("message", msg);
        map.put("code", code);
        return map;
    }

    public static void main(String[] args) {
        Map<String,String> map = new HashMap<>();
        Map<String, Object> aaa=  HttpClientss.getDateFromERP("http://125.46.78.164:8085/jeecg-boot/wmsNInterface/getHesEmployeeList"
                ,HttpMethod.POST,map);
        System.out.println(aaa);
    }

    public static Map<String, Object> getDateFromERP(String url, HttpMethod method,Map<String,String> map) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        // headers.add("data-Type", "json");
        // headers.add("Content-type", "application/json;charset=UTF-8");
        //headers.add("access-token", "123456");
       /* String nowDate = DateUtil.getDate();
        String str = nowDate + "|wmserp";
        String token = StrToMD5.string2MD5(str);
        map.put("token",token);*/
        JSONObject json = (JSONObject) JSONObject.toJSON(map);
        logger.info("----------------发送url:------------"+url);
        logger.info("----------------发送参数:------------"+json);
        HttpEntity<JSONObject> requestEntity = new HttpEntity<>(json, headers);
        RestTemplate client = new RestTemplate();
        ResponseEntity<String> response = client.exchange(url, method, requestEntity, String.class);
        String res = response.getBody();
        JSONObject object = JSON.parseObject(res);
        logger.info("AGV返回object:"+object);
        String id = object.getString("id");
        Integer code = object.getInteger("code");
        String msg = object.getString("msg");
        String result = object.getString("result");
        String data = object.getString("data");
        Map<String, Object> resulTmap = new HashMap<>();
        resulTmap.put("id", id);
        resulTmap.put("msg", msg);
        resulTmap.put("code", code);
        resulTmap.put("result",result);
        resulTmap.put("data",data);
        logger.info("AGV返回resultMap:"+resulTmap);
        return resulTmap;
    }

    public static Map<String, Object> getDateFromERP3(String url, HttpMethod method,List<Map<String,Object>> list) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        Object json =  JSONArray.toJSON(list);
        //JSONObject json = JSONObject.parseObject(JSONObject.toJSONString(list));
        //JSONObject json = JSONObject.parseObject();
        logger.info("----------------发送url:------------"+url);
        logger.info("----------------发送参数:------------"+json);
        HttpEntity<Object> requestEntity = new HttpEntity<>(json, headers);
        RestTemplate client = new RestTemplate();
        ResponseEntity<String> response = client.exchange(url, method, requestEntity, String.class);
        String res = response.getBody();
        JSONObject object = JSON.parseObject(res);
        logger.info("第三方返回object:"+object);

        Integer code = object.getInteger("code");
        String msg = object.getString("msg");
        String data = object.getString("data");
        String result = object.getString("result");
        Map<String, Object> resulTmap = new HashMap<>();
        resulTmap.put("msg", msg);
        resulTmap.put("code", code);
        resulTmap.put("result",result);
        resulTmap.put("data",data);
        return resulTmap;
    }

    public static Map<String, Object> getDateFromERP2(String url, HttpMethod method,Map<String,Object> map) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        JSONObject json = (JSONObject) JSONObject.toJSON(map);
        logger.info("----------------发送url:------------"+url);
        logger.info("----------------发送参数:------------"+json);
        HttpEntity<JSONObject> requestEntity = new HttpEntity<>(json, headers);
        RestTemplate client = new RestTemplate();
        ResponseEntity<String> response = client.exchange(url, method, requestEntity, String.class);
        String res = response.getBody();
        JSONObject object = JSON.parseObject(res);
        logger.info("第三方返回object:"+object);

        Integer code = object.getInteger("code");
        String msg = object.getString("msg");
        String data = object.getString("data");
        String result = object.getString("result");
        Map<String, Object> resulTmap = new HashMap<>();
        resulTmap.put("msg", msg);
        resulTmap.put("code", code);
        resulTmap.put("result",result);
        resulTmap.put("data",data);
        return resulTmap;
    }

    /*public static Map<String, Object> getDateFromERP(String url, HttpMethod method,Map<String,String> map) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.add("Data-Type", "json");
        //headers.add("access-token", "123456");
        String nowDate = DateUtil.getDate();
        String str = nowDate + "|wmserp";
        String token = StrToMD5.string2MD5(str);
        map.put("token",token);
        JSONObject json = (JSONObject) JSONObject.toJSON(map);
        System.out.println("----------------发送url:------------"+url);
        System.out.println("----------------发送参数:------------"+json);
        HttpEntity<JSONObject> requestEntity = new HttpEntity<>(json, headers);
        RestTemplate client = new RestTemplate();
        ResponseEntity<String> response = client.exchange(url, method, requestEntity, String.class);
        String res = response.getBody();
        JSONObject object = JSON.parseObject(res);
        Boolean success = object.getBoolean("success");
        String code = object.getString("code");
        String msg = object.getString("message");
        String data = object.getString("result");
        Map<String, Object> resulTmap = new HashMap<>();
        resulTmap.put("success", success != null ? success.toString() : "false");
        resulTmap.put("message", msg);
        resulTmap.put("code", code);
        System.out.println("ERP返回resulTmap:"+resulTmap);
        resulTmap.put("data", data);
        // List<EventColAttr> list = JSONObject.parseArray(array.toJSONString(), EventColAttr.class);
        // Object name = ((JSONObject)jsonArray.get(0)).get("employeeName");
        *//*for(int i=0;i<jsonArray.size();i++){
            JSONObject obj= (JSONObject) jsonArray.get(i);
            System.out.println(obj.get("employeeName"));
        }*//*
        return resulTmap;
    }*/

    public static void doPostOrGet(String pathUrl, HttpMethod method, String data){
        OutputStreamWriter out = null;
        BufferedReader br = null;
        String result = "";
        try {
            URL url = new URL(pathUrl);
            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //请求方式
            conn.setRequestMethod("POST");
            //conn.setRequestMethod("GET");

            //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");

            //DoOutput设置是否向httpUrlConnection输出，DoInput设置是否从httpUrlConnection读入，此外发送post请求必须设置这两个
            conn.setDoOutput(true);
            conn.setDoInput(true);

            /**
             * 下面的三句代码，就是调用第三方http接口
             */
            //获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            //发送请求参数即数据
            out.write(data);
            //flush输出流的缓冲
            out.flush();

            /**
             * 下面的代码相当于，获取调用第三方http接口后返回的结果
             */
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            //构造一个字符流缓存
            br = new BufferedReader(new InputStreamReader(is));
            String str = "";
            while ((str = br.readLine()) != null){
                result += str;
            }
            System.out.println(result);
            //关闭流
            is.close();
            //断开连接，disconnect是在底层tcp socket链接空闲时才切断，如果正在被其他线程使用就不切断。
            conn.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (out != null){
                    out.close();
                }
                if (br != null){
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
